package org.example.k8s_cloudplatform.K8S_mapper;

import io.kubernetes.client.Exec;
import io.kubernetes.client.custom.Quantity;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.*;
import org.example.k8s_cloudplatform.entity.Pod;
import org.example.k8s_cloudplatform.utils.K8S_util;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.util.*;

@SuppressWarnings("UnusedReturnValue")
@Repository
public class K8SPodMapper {
    private final ApiClient apiClient = K8S_util.client;
    private final CoreV1Api coreApi = K8S_util.coreApi;

    public V1Pod create(Pod input) throws ApiException {
        V1Pod res;
        V1Pod pod = new V1Pod();

        V1ObjectMeta metadata = new V1ObjectMeta();
        metadata.setName(input.getName());
        metadata.setNamespace(input.getUserID().toString());
        //标签设置
        Map<String, String> labels = new HashMap<>();
        labels.put("userID",input.getUserID()+"");
        labels.put("name",input.getName());
        metadata.setLabels(labels);

        pod.setMetadata(metadata);

        List<String> args=new ArrayList<>();
        args.add("-c");
        if(input.getImageOS().equals("centos")){
            args.add("/usr/sbin/sshd;while true; do sleep 1000; done");
        }
        if (input.getImageOS().equals("ubuntu")){
            args.add("service ssh start;while true; do sleep 1000; done");
        }

        V1PodSpec podSpec = new V1PodSpec();

        V1Container container = new V1Container();
        container.name(input.getName())
                .image("192.168.88.137:5000/" +input.getImageOS()+":"+input.getImageVersion())
                .command(Collections.singletonList("/bin/sh"))
                .args(args)
                .resources(new V1ResourceRequirements()
                        .putLimitsItem("cpu", new Quantity(String.format("%d", input.getCpu())))
                        .putLimitsItem("memory", new Quantity(String.format("%dMi", input.getMemory())))
                        .putRequestsItem("ephemeral-storage",new Quantity("2Gi"))
                );
        podSpec.containers(Collections.singletonList(container));

        pod.setSpec(podSpec);
        res = coreApi.createNamespacedPod(input.getUserID().toString(), pod, null, null, null);
        return res;
    }

    public V1Pod delete(Pod pod) throws ApiException{
        // 创建删除选项
        V1DeleteOptions deleteOptions = new V1DeleteOptions();
        deleteOptions.setPropagationPolicy("Foreground");
        //删除pod
        return coreApi.deleteNamespacedPod(pod.getName(), pod.getUserID().toString(), null, null,
                null, null, null,deleteOptions);
    }

    public Process addUser(Pod input,Integer userID) throws ApiException, IOException {
        Exec executor = new Exec(apiClient);
        // 获取 Pod 对象
        V1Pod pod = coreApi.readNamespacedPod(input.getName(), input.getUserID().toString(), null, null, null);
        String[] args = new String[0];
        // Ubuntu执行命令 useradd -m -s /bin/bash -p $(openssl passwd -1 <默认密码>)  user<用户ID>
        if (input.getImageOS().equals("ubuntu")) {
            args = new String[]{"/bin/bash",
                    "-c",
                    "echo \"$(openssl passwd -1 12345678)\" | useradd -m -s /bin/bash -p $(cat) user" + userID};
        }
        // Centos7执行命令 useradd -m -s /bin/bash user<用户ID> && echo "user<用户ID>:<默认密码>" | chpasswd
        if(input.getImageOS().equals("centos")&&input.getImageVersion().equals("7")){
            args = new String[]{"/bin/bash",
                    "-c",
                    "useradd -m -s /bin/bash user" + userID + "&&echo \"user" + userID + ":12345678\" | chpasswd"};
        }
        // Centos8执行命令 sed -i -r 's/^(.*pam_nologin.so)/#\1/' /etc/pam.d/sshd&&useradd -m -s /bin/bash user<用户ID> && echo "user<用户ID>:<默认密码>" | chpasswd
        if(input.getImageOS().equals("centos")&&input.getImageVersion().equals("8")){
            args = new String[]{"/bin/bash",
                    "-c",
                    "sed -i -r 's/^(.*pam_nologin.so)/#\\1/' /etc/pam.d/sshd&&" +
                            "useradd -m -s /bin/bash user" + userID + "&&" +
                            "echo \"user" + userID + ":12345678\" | chpasswd"};
        }

        return  executor.exec(pod,args, false, false);
    }

    public Process deleteUser(Pod input,Integer userID) throws ApiException, IOException {
        Exec executor = new Exec(apiClient);
        // 获取 Pod 对象
        V1Pod pod = coreApi.readNamespacedPod(input.getName(), input.getUserID().toString(), null, null, null);
        // 执行命令 userdel -r user<用户ID>
        String[] args = {
                "/bin/bash",
                "-c",
                "userdel -r user" + userID
        };
        return executor.exec(pod, args, false, false);
    }
}
